package com.zys.el.time.common.exception;


import com.zys.el.time.common.Result;
import com.zys.el.time.common.exception.sql.SqlException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class}) // 通知加了@Service的类
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * SQL异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class) // SQL完整性约束冲突异常（直译）
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());

        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2].split("'")[1] + "已存在";
            return Result.fail(msg);
        }

        return Result.fail("未知错误");
    }

    /**
     * 插入记录异常
     * @param ex
     * @return
     */
    @ExceptionHandler(SqlException.class)
    public Result exceptionHandler(SqlException ex){
        String msg = ex.getMessage();
        log.error(msg);
        return Result.fail(msg);
    }

    /**
     * 业务异常处理方法
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public Result exceptionHandler(CustomException ex){
        log.error(ex.getMessage());

        return Result.fail(ex.getMessage());
    }

}
